"ui";
importClass(android.graphics.Color);
importClass(android.graphics.drawable.GradientDrawable);
// 数据
var storage = storages.create("autotouchDouyin");
// 库
var { swipeRandom } = require("./common/common.js");
var douyinUtils = require("./common/douyinUtils.js");
const project = require('./project.json');

//参数声明
var isPulic = true;
var appPackageName = "com.ss.android.ugc.aweme";
var deviceWidth = device.width;
var deviceHeight = device.height;
var picJizhunWidth = storage.get("picJizhunWidth", 1)
var picJizhunHeight = storage.get("picJizhunHeight", 1)
var version = project.versionName;
var yanchi = 500; // 点击后停顿
var yanchi1 = 1000; // 点击前停顿
var yanchi2 = 2000; // 点击后停顿
var yanchi3 = 3000; // 点击后停顿
var yanchi5 = 5000; // 点击后停顿
var pointObj = { pinglun: {}, pointObj };
var dzPicChaObj = { weizhi: {}, dzPicCha: 0 };

myLogFunc('当前基准：', picJizhunWidth, picJizhunHeight)
var floatyConsole;
var myLogStr = " ";
var pinglunReg = "跑断腿|捡我|捡粉|活的|自媒体|必回|诚信|互|活跃|大学生";
var sixinReg = "有票|嘎嘎活";
var pinglunsList = "来互,欢迎来互，有赞必回,诚信的来看数据就懂！";

ui.layout(
    <ScrollView>
        <vertical>
            <appbar>
                <toolbar id="appTitle" title="抖音软件" />
            </appbar>
            <Switch id="autoService" text="无障碍服务" checked="{{auto.service != null}}" padding="8 8 8 8" textSize="15sp" />
            <horizontal>
                <text text="  激活码：" gravity="left" />
                <input id="jihuoma" hint="请输入注册码" textSize="15sp" inputType="text" gravity="left" w="*" />
            </horizontal>
            <horizontal>
                <text text="  抖音客户端：" gravity="left" />
                <spinner id="khd" entries="抖音|抖音极速版" />
            </horizontal>
            <horizontal>
                <text text="  流程选择：" gravity="left" />
                <spinner id="liucheng" entries="主页刷视频|搜索视频|批量取关" />
            </horizontal>
            <vertical marginTop="8sp" bg="#99FE01">
                <horizontal>
                    <text text="  评论过滤模式：" gravity="left" />
                    <spinner id="glms" entries="评论包含关键词" />
                </horizontal>
                <horizontal>
                    <text text="  私信内容：" gravity="left" />
                    <input id="sixin" hint="请填写私信内容！" textSize="15sp" gravity="left" w="*" />
                </horizontal>
                <horizontal >
                    <text text="  私信关键词：" gravity="left" />
                    <input id="sixinKeys" hint="多个用|分割，空表示不过滤" textSize="15sp" gravity="left" w="*" />
                </horizontal>
                <horizontal marginTop="6sp">
                    <text text="  评论内容：" gravity="left" />
                    <input id="pingluns" hint="请填写回复评论的内容,分割！" textSize="15sp" gravity="left" w="*" />
                </horizontal>
                <horizontal >
                    <text text="  评论关键词：" gravity="left" />
                    <input id="keys" hint="多个用|分割，空表示不过滤" textSize="15sp" gravity="left" w="*" />
                </horizontal>
                <horizontal>
                    <text text="  评论区最多翻页：" gravity="left" />
                    <input id="pinglunfanye" hint="评论区翻页" textSize="15sp" inputType="number" gravity="center" />
                </horizontal>
            </vertical>

            <horizontal marginTop="10sp" padding="12sp" bg="#FFFF01">
                <checkbox id="isPinglun" text="回复评论" />
                <checkbox id="isDianzan" text="评论点赞" />
                <checkbox id="isSixin" text="关注私信" />
            </horizontal>

            <vertical marginTop="8sp" bg="#E63F31">
                <horizontal>
                    <text text="  取关目标：" gravity="left" />
                    <spinner id="quguanrenqun" entries="相互关注|已关注" />
                </horizontal>
                <horizontal>
                    <text text="  保留包含字符人群：" gravity="left" />
                    <input id="quguanBaoliu" hint="保留名称包涵该字符的人，一般用于备注后" textSize="15sp" inputType="text" gravity="left" w="*" />
                </horizontal>
            </vertical>

            <horizontal marginTop="6sp">
                <text text="  运行总时间：" gravity="left" />
                <input id="yhsc" hint="时间(分钟)" textSize="15sp" inputType="number" gravity="center" />
                <text text="    喜欢概率：" gravity="left" />
                <input id="xhgl" hint="喜欢概率" textSize="15sp" inputType="number" gravity="center" />
            </horizontal>
            {/* <horizontal>
                <text text="  浏览作品时间：" gravity="left" />
                <input id="jg" hint="最小值" textSize="15sp" inputType="number" gravity="center" />
                <text text="----" gravity="center" />
                <input id="jg1" hint="最大值" textSize="15sp" inputType="number" gravity="center" />
                <text text="   秒" gravity="left" />
            </horizontal> */}

            <horizontal marginTop="10sp" padding="12sp" bg="#FFC801">
                <checkbox id="logWindow" text="日志窗口" />
                <checkbox id="logFile" text="日志文件" />
            </horizontal>
            <horizontal marginTop="6sp">
                <text text="  浏览作品：" gravity="left" />
                <text id="liulanNum" text="88" gravity="left" />
                <text text="   ----" gravity="center" />
                <text text="  评论内容：" gravity="left" />
                <text id="pinglunNum" text="888" gravity="left" />
                <button id="cleanCon" text="重置" marginLeft="6sp" />
            </horizontal>
            <horizontal marginTop="6sp">
                <button id="start" text="开始运行" layout_weight="1" style="Widget.AppCompat.Button.Colored" />
            </horizontal>
            <text text="   温馨提示：" gravity="left" marginTop="6sp" />
            <text text="   1.软件根据关键词是否进行交互；" gravity="left" />
            <text text="   2.关键词尽量精准，才能使账号更加垂直；" gravity="left" />
            <text text="   3.可设置多个关键词，分隔符“|”；" gravity="left" />
            <text text="   4.例如：剪辑,影视,观影,60帧等；" gravity="left" />
            <text text="   5.关键词尽可能多而精准；" gravity="left" />
            <horizontal>
                <text text="   系统提示：" gravity="left" />
                <checkbox id="支持" text="本软件无需root权限。" checked="true" />
            </horizontal>

            <horizontal>
                <text id="appVersion" text="   当前软件版本：  " gravity="left" />
                <text id="androidVer" textSize="15sp" />
            </horizontal>


        </vertical>
    </ScrollView>
);

ui.androidVer.text("   本机安卓版本：" + device.release + "");
ui.appVersion.text("   当前软件版本：" + version + "     ");
ui.appTitle.title = "抖音引流辅助 V" + version;
ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});


//记录按键被按下时的触摸坐标
var x = 0, y = 0;
//记录按键被按下时的悬浮窗位置
var windowX, windowY;
// 悬浮窗
var floatyWindow;

function xuanfuFunc() {
    myLogFunc('开启悬浮窗')
    floatyWindow = floaty.window(
        <horizontal >
            <button id="floatyAction" text="运" textSize="12sp" w="35" h="35"></button>
            <button id="mySet" text="设置" textSize="12sp" w="40" h="35" bg="#87CFE8" marginLeft="8sp" />
            <button id="myExit" text="退出" textSize="12sp" w="40" h="35" bg="#02FE99" marginLeft="2sp" />
        </horizontal >
    );

    floatyWindow.floatyAction.setOnTouchListener(function (view, event) {
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x = event.getRawX();
                y = event.getRawY();
                windowX = floatyWindow.getX();
                windowY = floatyWindow.getY();
                return true;
            case event.ACTION_MOVE:
                //移动手指时调整悬浮窗位置
                floatyWindow.setPosition(windowX + (event.getRawX() - x), windowY + (event.getRawY() - y));
                return true;
            case event.ACTION_UP:
                //手指弹起时如果偏移很小则判断为点击
                if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                    // myLogFunc('点击')
                    floatyActionOnClick();
                }
                return true;
        }
        return true;
    });

    floatyWindow.mySet.setVisibility(8);
    floatyWindow.myExit.setVisibility(8);
    setBackgroundRoundRounded(floatyWindow.floatyAction, true);

    floatyWindow.mySet.on("click", function () {
        app.launchPackage("com.daoyikeji.douyinzdh");
    })

    floatyWindow.myExit.on("click", function () {
        ui.finish()
        // exit()
    })
}

function setBackgroundRoundRounded(view, bloo) {
    gradientDrawable = new GradientDrawable();
    gradientDrawable.setShape(GradientDrawable.RECTANGLE);
    if (bloo) {
        gradientDrawable.setColor(Color.GREEN);
    } else {
        gradientDrawable.setColor(Color.RED);
    }
    gradientDrawable.setCornerRadius(80);
    view.setBackground(gradientDrawable);
}


function floatyActionOnClick() {
    if (floatyWindow.floatyAction.getText() == '运') {
        setBackgroundRoundRounded(floatyWindow.floatyAction, false);
        floatyWindow.mySet.setVisibility(0);
        floatyWindow.myExit.setVisibility(0);
        floatyWindow.floatyAction.setText('停');
        myLogFunc('暂停')
        threads.shutDownAll()
    } else {
        floatyWindow.mySet.setVisibility(8);
        floatyWindow.myExit.setVisibility(8);
        setBackgroundRoundRounded(floatyWindow.floatyAction, true);
        floatyWindow.floatyAction.setText('运');
        myLogFunc('重启')
        mainFunc(true)
    }
}

function myLogFunc() {
    log(arguments)
    myLogStr += '\n' + String(arguments[0])
}

function xuanfuLogFunc() {
    floatyConsole = floaty.rawWindow(
        <frame gravity="left">
            <text id="myLog" text="日志" textColor="#ffffff" alpha="0.5" bg="#000000" textSize="10sp" ellipsize="marquee" gravity="bottom" />
        </frame>
    );

    floatyConsole.setSize(300, 200)
    floatyConsole.setPosition(30, deviceHeight - 880);
    floatyConsole.setTouchable(false)
    floatyConsole.myLog.text(" " + myLogStr + " ");

    floatyConsoleTimer = setInterval(() => {
        floatyConsole.myLog.text(" " + myLogStr + " ");
    }, 2000);
}


function saveconfig() {
    storage.put("jihuoma", ui.jihuoma.text());
    storage.put("liucheng", ui.liucheng.getSelectedItemPosition());
    storage.put("quguanrenqun", ui.quguanrenqun.getSelectedItemPosition());
    storage.put("quguanBaoliu", ui.quguanBaoliu.text());
    storage.put("sixin", ui.sixin.text());
    storage.put("sixinKeys", ui.sixinKeys.text());
    storage.put("keys", ui.keys.text());
    storage.put("pingluns", ui.pingluns.text());
    storage.put("isPinglun", ui.isPinglun.checked);
    storage.put("isDianzan", ui.isDianzan.checked);
    storage.put("isSixin", ui.isSixin.checked);
    storage.put("logFile", ui.logFile.checked);
    storage.put("logWindow", ui.logWindow.checked);
    storage.put("yhsc", ui.yhsc.text());
    storage.put("xhgl", ui.xhgl.text());
    storage.put("pinglunfanye", ui.pinglunfanye.text());
    // storage.put("jg", ui.jg.text());
    // storage.put("jg1", ui.jg1.text());
    myLogFunc('已保存配置')
}

function readconfig() {
    ui.jihuoma.text(storage.get("jihuoma", ""));
    if (parseInt(storage.get("liucheng", 0))) {
        ui.liucheng.setSelection(parseInt(storage.get("liucheng", 0)));
    };
    if (parseInt(storage.get("quguanrenqun", 0))) {
        ui.quguanrenqun.setSelection(parseInt(storage.get("quguanrenqun", 0)));
    };
    ui.quguanBaoliu.text(storage.get("quguanBaoliu", "👍🏻"));
    ui.sixin.text(storage.get("sixin", "诚信来互有赞必回随迟必到，欢迎来互！"));
    ui.sixinKeys.text(storage.get("sixinKeys", "有票|嘎嘎活"));
    ui.keys.text(storage.get("keys", "跑断腿|捡我|捡粉|活的|自媒体|必回|诚信|互|活跃|大学生"));
    ui.pingluns.text(storage.get("pingluns", "来互,欢迎来互,有赞必回 随迟必到,主打一个诚信 必回,诚信的来看数据就懂！"));
    ui.isPinglun.checked = Boolean(storage.get("isPinglun", false));
    ui.logFile.checked = Boolean(storage.get("logFile", false));
    ui.logWindow.checked = Boolean(storage.get("logWindow", false));
    ui.isDianzan.checked = Boolean(storage.get("isDianzan", false));
    ui.isSixin.checked = Boolean(storage.get("isSixin", false));
    ui.yhsc.text(storage.get("yhsc", ""));
    ui.xhgl.text(storage.get("xhgl", "60"));
    ui.pinglunfanye.text(storage.get("pinglunfanye", "5"));
    // ui.jg.text(storage.get("jg", "2"));
    // ui.jg1.text(storage.get("jg1", "5"));
    ui.liulanNum.text(String(storage.get("liulanNum", "0")));
    ui.pinglunNum.text(String(storage.get("pinglunNum", "0")));
}
// 直接读取存贮值
readconfig()
// 请求服务器
function autoServerFunc() {
    myLogFunc("http")
    let req = http.postJson("http://123.60.43.199:8866/main/v1/auto/dyYl", {
        activationCode: storage.get("jihuoma", ""),
        aap: "dyYl",
        deviceWidth: deviceWidth,
        deviceHeight: deviceHeight,
        brand: device.brand,
        versionCode: project.versionCode,
        release: device.release,
        sdkInt: device.sdkInt,
        androidId: device.getAndroidId(),
        fingerprint: device.fingerprint,
        mac: device.getMacAddress(),
        // iMEI: device.getIMEI(),
        startTime: new Date().getTime()
        // ipAddress: device.getIpAddress()
    });
    let rJson = req.body.json();
    if (rJson.code != 200) {
        let message = rJson.message ? rJson.message : "服务异常请联系客服！";
        toastLog(message)
        sleep(1000)
        exit()
        sleep(2000)
        ui.finish()
    } else {
        myLogFunc("服务成功注册！")
    }
}


function searchLiuchengFunc() {
    myLogFunc("搜索流程")
    // 获取坐标
    pointObj = getPointFunc();
    // 执行点赞 可能点到“挑战”
    DzFunc()
    sleep(1000)
    // 获取点赞后位置信息
    let dzPicPorit = dzPicFunc(true)
    // 计算点赞图片与中心位置差值
    if (pointObj.xihuan.y && dzPicPorit.y) {
        dzPicChaObj.dzPicCha = dzPicPorit.y - pointObj.xihuan.y;
        myLogFunc("点赞图片匹配信息", dzPicChaObj)
    } else {
        myLogFunc("位置信息存在偏差，请重启程序")
    }
    // 点击评论进入评论区
    myLogFunc('进入评论区')
    click(pointObj.pinglun.x, pointObj.pinglun.y)
    sleep(2000)
    myLogFunc("检测评论页");
    if (text("善语结善缘，恶言伤人心").exists()) {
        myLogFunc("在评论区页面");
    }
    let t = textMatches(".*条评论.*|.*暂无评论.*").find();
    if (t) {
        myLogFunc("加载评论完成");
    }
    // 空评论区
    if (text("期待你的评论").exists()) {
        myLogFunc('空评论区')
        back();
        sleep(1000);
        back();
        sleep(2000);
    } else {
        sleep(1000);
        for (let index = 0; index < Number(storage.get("pinglunfanye", "5")); index++) {
            sleep(1000)
            className("androidx.recyclerview.widget.RecyclerView").findOne().children().forEach(child => {
                // let target = child.findOne(id("title")); // 评论者
                // let target = child.findOne(id("dex")); // 评论者关系
                let target1 = child.findOne(id("content")); // 评论
                let target = child.findOne(descStartsWith("赞")); // 赞
                let target2 = child.findOne(className("android.widget.TextView").text("回复")); // 回复
                // target.click();
                if (target1) { // 可能存在空元素
                    let contStr = String(target1.text());
                    // 符合匹配规则并且有回复按钮 因为有些信息没有回复按钮
                    if (contStr.match(pinglunReg) && target2) {
                        let bounds = target.bounds()
                        let bounds2 = target2.bounds()
                        myLogFunc("进行评论")
                        let anquanqu = deviceHeight - 200;
                        // 判断是否在安全区
                        if (bounds.centerY() < anquanqu) {
                            click(bounds2.centerX(), bounds2.centerY())
                            myLogFunc('评论：', contStr)
                            let sentText = getRandomNumber(0, pinglunsList.length - 1)
                            sentText = pinglunsList[sentText]
                            douyinUtils.sentMsg(sentText)
                            sleep(2000)
                        } else {
                            myLogFunc('安全区外内容', contStr)
                        }
                    } else {
                        myLogFunc('跳过评论：', contStr)
                    }
                }
            })
            sleep(1000)
            douyinUtils.commentNextPage(1);
            sleep(2000)
            if (text('暂时没有更多了').findOnce()) {
                back();
                sleep(3000);
                myLogFunc('暂时没有更多了')
                break;
            }
        }
        // 关闭评论页
        back();
        sleep(1000);
    }

    // 循环执行
    while (true) {
        loopShipinFunc();
    }

}

function zhuyeLiuchengFunc() {
    // 防止程序卡死
    threads.start(function () {
        let jiancePoint = setTimeout(() => {
            myLogFunc('定时器执行了')
            clearTimeout(jiancePoint)
            if (!pointObj.pinglun.y) {
                toastLog("捕获坐标异常，重启应用！")
                sleep(1000)
                openAppSetting(appPackageName);
                text(app.getAppName(appPackageName)).waitFor();//通过包名获取已安装的应用名称，判断是否已经跳转至该app的应用设置界面
                let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*)/).findOne();//在app的应用设置界面找寻包含“强”，“停”，“结”，“行”的控件
                if (is_sure.enabled()) {//判断控件是否已启用（想要关闭的app是否运行）
                    sleep(500);
                    is_sure.click();//结束应用的控件如果无法点击，需要在布局中找寻它的父控件，如果还无法点击，再上一级控件，本案例就是控件无法点击
                    sleep(1000);
                    textMatches(/(.*确.*|.*定.*)/).findOne().click();//需找包含“确”，“定”的控件
                    myLogFunc("应用已被关闭");
                    sleep(1000);
                    back();
                    sleep(1000);
                    mainFunc();
                } else {
                    myLogFunc("应用不能被正常关闭或不在后台运行");
                    back();
                    exit();
                }
            }
            myLogFunc('定时器线程关闭了')
        }, 60000);
    })

    // 获取坐标
    pointObj = getPointFunc();
    // 存储在本地存储
    // storage.put("pointObj", pointObj)
    // 执行点赞 可能点到“挑战”
    DzFunc()
    sleep(1000)
    // 获取点赞后位置信息
    let dzPicPorit = dzPicFunc(true)
    // 计算点赞图片与中心位置差值
    if (pointObj.xihuan.y && dzPicPorit.y) {
        dzPicChaObj.dzPicCha = dzPicPorit.y - pointObj.xihuan.y;
        myLogFunc("点赞图片匹配信息", dzPicChaObj)
    } else {
        myLogFunc("位置信息存在偏差，请重启程序")
    }
    // 点击评论进入评论区
    myLogFunc('进入评论区')
    click(pointObj.pinglun.x, pointObj.pinglun.y)
    sleep(2000)
    myLogFunc("检测评论页");
    if (text("善语结善缘，恶言伤人心").exists()) {
        myLogFunc("在评论区页面");
    }
    let t = textMatches(".*条评论.*|.*暂无评论.*").find();
    if (t) {
        myLogFunc("加载评论完成");
    }
    // 空评论区
    if (text("期待你的评论").exists()) {
        myLogFunc('空评论区')
        back();
        sleep(1000);
        back();
        sleep(2000);
    } else {
        sleep(1000);
        for (let index = 0; index < Number(storage.get("pinglunfanye", "5")); index++) {
            sleep(1000)
            className("androidx.recyclerview.widget.RecyclerView").findOne().children().forEach(child => {
                // let target = child.findOne(id("title")); // 评论者
                // let target = child.findOne(id("dex")); // 评论者关系
                let target1 = child.findOne(id("content")); // 评论
                let target = child.findOne(descStartsWith("赞")); // 赞
                let target2 = child.findOne(className("android.widget.TextView").text("回复")); // 回复
                // target.click();
                if (target1) { // 可能存在空元素
                    let contStr = String(target1.text());
                    // 符合匹配规则并且有回复按钮 因为有些信息没有回复按钮
                    if (contStr.match(pinglunReg) && target2) {
                        let bounds = target.bounds()
                        let bounds2 = target2.bounds()
                        myLogFunc("进行评论")
                        let anquanqu = deviceHeight - 200;
                        // 判断是否在安全区
                        if (bounds.centerY() < anquanqu) {
                            click(bounds2.centerX(), bounds2.centerY())
                            myLogFunc('评论：', contStr)
                            let sentText = getRandomNumber(0, pinglunsList.length - 1)
                            sentText = pinglunsList[sentText]
                            douyinUtils.sentMsg(sentText)
                            sleep(2000)
                        } else {
                            myLogFunc('安全区外内容', contStr)
                        }
                    } else {
                        myLogFunc('跳过评论：', contStr)
                    }
                }
            })
            sleep(1000)
            douyinUtils.commentNextPage(1);
            sleep(2000)
            if (text('暂时没有更多了').findOnce()) {
                back();
                sleep(3000);
                myLogFunc('暂时没有更多了')
                break;
            }
        }
        // 关闭评论页
        back();
        sleep(1000);
    }

    // 循环执行
    while (true) {
        loopShipinFunc();
    }

}


function loopShipinFunc() {
    myLogFunc('@@又一轮循环')
    let pinglunlem = 0;
    let liulanNum = storage.get("liulanNum", "0")
    liulanNum = Number(liulanNum) + 1;
    storage.put("liulanNum", String(liulanNum));
    // 下一个视频
    nextVideo()
    if (desc("点击进入直播间按钮").exists()) {
        sleep(1000)
        myLogFunc("不进入直播间")
        return
    }
    sleep(500)
    // 执行点赞
    DzFunc()
    sleep(1000)
    // 获取点赞后位置信息
    let dzPicPoritXz = dzPicFunc()
    // 计算点赞后坐标位置是否位移
    let dianzanCha = dzPicChaObj.weizhi.y - dzPicPoritXz.y;
    // 如果位移
    if (Math.abs(dianzanCha) > 10) {
        myLogFunc('操作位置浮动', dianzanCha)
        // 更新新坐标
        dzPicChaObj.weizhi = dzPicPoritXz;
        for (let key in pointObj) {
            if (Object.hasOwnProperty.call(pointObj, key)) {
                let forObj = pointObj[key];
                pointObj[key].y = forObj.y - dianzanCha
            }
        }
        myLogFunc('操作区更新后', pointObj)
    } else {
        myLogFunc('操作位置不变')
    }

    // 点击评论进入评论区
    myLogFunc('进入评论区')
    click(pointObj.pinglun.x, pointObj.pinglun.y)
    sleep(2000)
    myLogFunc("检测评论页");
    if (text("善语结善缘，恶言伤人心").exists()) {
        myLogFunc("在评论区页面");
    }
    let t = textMatches(".*条评论.*|.*暂无评论.*").find();
    if (t) {
        myLogFunc("加载评论完成");
    }
    if (text("期待你的评论").findOnce()) {
        myLogFunc('空评论区')
        back();
        sleep(1000);
        back();
        sleep(2000);
        return
    }

    sleep(1000);
    for (let index = 0; index < Number(storage.get("pinglunfanye", "5")); index++) {
        sleep(1000)
        className("androidx.recyclerview.widget.RecyclerView").findOne().children().forEach(child => {
            let title = child.findOne(id("title")); // 评论者
            // let target = child.findOne(id("dex")); // 评论者关系
            let target1 = child.findOne(id("content")); // 评论
            let target = child.findOne(descStartsWith("赞")); // 赞
            let target2 = child.findOne(className("android.widget.TextView").text("回复")); // 回复
            // target.click();
            if (target1) { // 可能存在空元素
                let contStr = String(target1.text());
                // 符合匹配规则并且有回复按钮 因为有些信息没有回复按钮
                if (target2) {
                    let titleBounds = title.bounds()
                    let bounds = target.bounds()
                    let bounds2 = target2.bounds()
                    let anquanqu = deviceHeight - 200;
                    // 私信流程
                    if (Boolean(storage.get("isSixin", false))) {
                        if (contStr.match(sixinReg)) {
                            let str = storage.get("sixin", "诚信来互有赞必回随迟必到，欢迎来互！");
                            // 判断是否在安全区
                            if (bounds.centerY() < anquanqu) {
                                click(titleBounds.centerX(), titleBounds.centerY())
                                sleep(2000)
                                myLogFunc('关注私信：' + String(contStr))
                                if (className("android.widget.TextView").text("关注").clickable(true).exists() ) {
                                    log(1)
                                    className("android.widget.TextView").text("关注").clickable(true).findOne().click()
                                    sleep(1000)
                                    desc('私信').findOne().click()
                                    sleep(1500)
                                    douyinUtils.sentSixinMsg(str)
                                    log(str)
                                    sleep(500)
                                    back()
                                    sleep(1000)
                                    back()
                                    
                                } else {
                                    log(2)
                                    desc('私信').findOne().click()
                                    sleep(1500)
                                    douyinUtils.sentSixinMsg(str)
                                    log(str)
                                    sleep(500)
                                    back()
                                    sleep(1000)
                                    back()
                                }
                            } else {
                                myLogFunc('安全区外内容', contStr)
                            }
                        }
                    }
                    if (contStr.match(pinglunReg)) {
                        // 判断是否在安全区
                        if (bounds.centerY() < anquanqu) {
                            pinglunlem = pinglunlem + 1;
                            click(bounds2.centerX(), bounds2.centerY())
                            myLogFunc('评论：' + String(contStr))
                            let sentText = getRandomNumber(0, pinglunsList.length - 1)
                            sentText = pinglunsList[sentText]
                            douyinUtils.sentMsg(sentText)
                            let pinglunNum = storage.get("pinglunNum", "0")
                            pinglunNum = Number(pinglunNum) + 1;
                            storage.put("pinglunNum", String(pinglunNum));
                            sleep(2000)
                        } else {
                            myLogFunc('安全区外内容', contStr)
                        }
                    }
                    

                }else {
                    myLogFunc('跳过评论：' + String(contStr))
                }
            }
        })
        sleep(1000)
        douyinUtils.commentNextPage(1);
        sleep(2000)
        if (text('暂时没有更多了').findOnce()) {
            back();
            sleep(3000);
            myLogFunc('暂时没有更多了')
            break;
        }
    }
    sleep(1000);
    if (pinglunlem > 1) {
        myLogFunc("该评论区已留言！")
        let sentText = getRandomNumber(0, pinglunsList.length - 1)
        sentText = pinglunsList[sentText]
        douyinUtils.sentMsg(sentText)
    }
    sleep(1000);
    // 关闭评论页
    back();
    sleep(1000);

}

function mainFunc(again) {
    主线程 = threads.start(function () {
        myLogFunc("主线程启动")
        // 检查无障碍服务是否已经启用，如果没有启用则跳转到无障碍服务启用界面，并等待无障碍服务启动；当无障碍服务启动后脚本会继续运行。
        // auto.waitFor()
        // 注册服务
        myLogFunc("server")
        // autoServerFunc()
        sleep(1000)
        //截图权限自动化安卓版本高于Android 9
        if (device.sdkInt > 27) {
            //等待截屏权限申请并同意
            threads.start(function () {
                if (device.brand == "HUAWEI") {
                    packageName('com.android.systemui').text('允许').waitFor();
                    text('允许').click();
                } else {
                    packageName('com.android.systemui').text('立即开始').waitFor();
                    text('立即开始').click();
                }
            });
        }
        //申请截屏权限
        if (!again) {
            if (!requestScreenCapture()) {
                toast("请求截图失败");
                exit()
            }
        }
        myLogFunc('分辨率', deviceWidth, deviceHeight)
        sleep(1000)
        myLogFunc('监听窗口')
        douyinUtils.checkOthers();

        //等待
        sleep(1000)
        myLogFunc("打开APP")
        // 打开app
        let appPackName = currentPackage();
        if (appPackName != appPackageName) {
            app.launchPackage(appPackageName);
            myLogFunc("正在运行请稍等")
            if (isPulic) {
                sleep(10000)
            } else {
                sleep(1000)
            }
            myLogFunc("程序运行中")
        } else {
            myLogFunc("正在运行抖音");
        }
        //等待
        sleep(1000)

        myLogFunc(new Date().getTime())

        // 按流程启动程序
        if (storage.get("liucheng", 0) == 0) {
            zhuyeLiuchengFunc()
        } else if (storage.get("liucheng", 0) == 1) {
            searchLiuchengFunc()
        } else if (storage.get("liucheng", 0) == 2) {
            batchQuguangFunc()
        }


        myLogFunc(new Date().getTime())

    })
}

// 重置计数
ui.cleanCon.on("click", function () {
    storage.put("liulanNum", String("0"));
    storage.put("pinglunNum", String("0"));
    ui.liulanNum.text(String(storage.get("liulanNum", "0")));
    ui.pinglunNum.text(String(storage.get("pinglunNum", "0")));
})

// 点击启动程序
ui.start.on("click", function () {
    // 保存配置
    saveconfig()
    //程序开始运行之前判断无障碍服务
    if (auto.service == null) {
        toastLog("请先开启无障碍服务！");
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
        return;
    } else {
        myLogFunc('已获取无障碍权限');
    }
    // 悬浮窗按钮
    if (!floaty.checkPermission()) {
        // 没有悬浮窗权限，提示用户并跳转请求
        toastLog("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
        floaty.requestPermission();
        return;
    } else {
        myLogFunc('已获取悬浮窗权限');
    }
    // 开启悬浮窗
    xuanfuFunc()
    // 开启日志悬浮窗
    if (Boolean(storage.get("logWindow", false))) {
        xuanfuLogFunc()
    }
    // 日志文件
    if (Boolean(storage.get("logFile", false))) {
        console.setGlobalLogConfig({
            "file": "/sdcard/autotouchDy.txt"
        });
    }
    // 格式化数据
    pinglunsList = storage.get("pingluns", "来互,欢迎来互,有赞必回 随迟必到,主打一个诚信 必回,诚信的来看数据就懂！");
    pinglunsList = pinglunsList.split(',');
    sixinReg = storage.get("sixinKeys", "有票|嘎嘎活");
    sixinReg = RegExp(sixinReg)
    pinglunReg = storage.get("keys", "跑断腿|捡我|捡粉|活的|自媒体|必回|诚信|互|活跃|大学生");
    pinglunReg = RegExp(pinglunReg)

    mainFunc()

});


// 批量取关
function batchQuguangFunc() {
    while (loopNum < 5) {
        autoQuanFunc()
    }
}

var loopNum = 0;
var firstName = '';

function autoQuanFunc() {
    className("androidx.recyclerview.widget.RecyclerView").scrollable(true).findOne().children().forEach(child => {
        let target = child.findOne(className("android.widget.TextView"));
        sleep(500)
        if (firstName == target.text()) {
            loopNum = loopNum + 1;
        } else {
            loopNum = 0;
        }
        firstName = target.text();
        if (target.text().indexOf(storage.get("quguanBaoliu", "👍🏻")) != -1) {
            log(target.text())
        } else {
            let target1 = child.findOne(className("android.widget.Button").text("互相关注"));
            if (target1) {
                log("互相关注", target.text())
                if (storage.get("quguanrenqun", 0) == 0) {
                    target1.parent().click();
                    sleep(900)
                    if (className("android.widget.TextView").text("取消关注").exists()) {
                        text("取消关注").findOne().click()
                        sleep(500)
                    }
                }
            } else {
                if (storage.get("quguanrenqun", 0) == 1) {
                    let target2 = child.findOne(className("android.widget.Button").text("已关注"));
                    if (target2) {
                        log("已关注", target.text())
                        target2.parent().click();
                        sleep(100)
                    }
                }
            }
        }
    });
    swipeRandom(device.width * 0.5, device.height - 150, device.width * 0.5, 220, 1500);
    sleep(1000)
}


// 函数方法
// 点赞
function DzFunc() {
    press(device.width * 0.4, device.height * 0.4, 10);
    sleep(50)
    press(device.width * 0.4, device.height * 0.4, 10);
}
// 坐标验证
function 坐标验证(weight) {
    // 验证坐标是当前屏幕内容 
    if (weight.left > 0 && weight.right > 0 && weight.top > 0 && weight.bottom > 0 && weight.top < deviceHeight && weight.bottom < deviceHeight) {
        return true
    } else {
        return false
    }
}
// 获取坐标
function getPointFunc() {
    let point = {};
    // 等待出现评论按钮
    myLogFunc('等待评论控件..')
    descStartsWith("评论").waitFor()
    myLogFunc('正在获取坐标..')
    // 评论
    var weight = descStartsWith("评论").findOne().bounds();
    if (this.坐标验证(weight)) {
        let obj = { x: weight.centerX(), y: weight.centerY() }
        point.pinglun = obj
        myLogFunc('评论坐标', obj)
    } else {
        point.pinglun = {}
        myLogFunc('获取评论坐标失败')
        point = storage.get("pointObj", { pinglun: {} })
        return point;
    }
    // 关注
    if (desc("关注").exists()) {
        weight = desc("关注").findOne().bounds();
        if (this.坐标验证(weight)) {
            let obj = { x: weight.centerX(), y: weight.centerY() }
            point.guanzhu = obj
            myLogFunc('关注坐标', obj)
        } else {
            point.guanzhu = {}
            myLogFunc('获取私信坐标失败')
        }
    } else {
        point.guanzhu = {}
        myLogFunc('未捕获关注坐标')
    }

    // 私信
    if (descStartsWith("私信").exists()) {
        weight = descStartsWith("私信").findOne().bounds();
        if (this.坐标验证(weight)) {
            let obj = { x: weight.centerX(), y: weight.centerY() }
            point.sixin = obj
            myLogFunc('私信坐标', obj)
        } else {
            point.sixin = {}
            myLogFunc('获取私信坐标失败')
        }
    } else {
        point.sixin = {}
        myLogFunc('未关注用户')
    }

    // 收藏
    weight = descStartsWith("未选中").findOne().bounds();
    if (this.坐标验证(weight)) {
        let obj = { x: weight.centerX(), y: weight.centerY() }
        point.shoucang = obj
        myLogFunc('收藏坐标', obj)
    } else {
        point.shoucang = {}
        myLogFunc('获取收藏坐标失败')
        point = storage.get("pointObj", { pinglun: {} })
        return point;
    }

    // 喜欢
    weight = descContains("，喜欢").findOne().children().findOne(className("android.widget.ImageView")).bounds();
    if (this.坐标验证(weight)) {
        let obj = { x: weight.centerX(), y: weight.centerY() }
        point.xihuan = obj;
        point.xihuanBlock = { left: weight.left, right: weight.right, top: weight.top, bottom: weight.bottom }
        myLogFunc('喜欢坐标', obj, point.xihuanBlock)
        picJizhunWidth = (weight.right - weight.left) / 94;
        picJizhunHeight = (weight.bottom - weight.top) / 94;
        storage.put("picJizhunWidth", picJizhunWidth)
        storage.put("picJizhunHeight", picJizhunHeight)
        myLogFunc('坐标基准')
        myLogFunc(picJizhunWidth)
    } else if (point.pinglun.y && point.shoucang.y) {
        let cha = point.shoucang.y - point.pinglun.y;
        point.xihuan = { x: point.pinglun.x, y: (point.pinglun.y - cha) }
        point.xihuanBlock = {}
    } else {
        point.xihuan = {}
        point.xihuanBlock = {}
        myLogFunc('获取喜欢坐标失败')
    }
    // 分享
    if (point.pinglun.y && point.shoucang.y) {
        let cha = point.shoucang.y - point.pinglun.y;
        point.fenxiang = { x: point.pinglun.x, y: (point.shoucang.y + cha) }
    } else {
        point.fenxiang = {}
    }

    myLogFunc("存储坐标集：", point)
    storage.put("pointObj", point)
    return point;
}
// 获取点赞后图标位置
function dzPicFunc(bloo) {
    let thisImgs = images.read("./res/点赞.png");
    thisImgs = images.scale(thisImgs, picJizhunWidth, picJizhunHeight)
    let p2 = findImage(captureScreen(), thisImgs);
    thisImgs.recycle();
    if (p2) {
        myLogFunc('点赞图片位置：', p2)
        if (bloo) {
            dzPicChaObj.weizhi = p2;
        }
        sleep(500)
        // 熄灭点赞
        let suijishu = Math.random() * 100
        if (Number(storage.get("xhgl", "60")) < suijishu) {
            click(p2.x, p2.y)
            sleep(500)
        }
        sleep(600)
        return p2;
    } else {
        myLogFunc('未获取到点赞图片信息，重新尝试')
        DzFunc()
        sleep(1000)
        let thisImgs = images.read("./res/点赞.png");
        thisImgs = images.scale(thisImgs, picJizhunWidth, picJizhunHeight)
        let p2 = findImage(captureScreen(), thisImgs);
        thisImgs.recycle();
        if (p2) {
            myLogFunc('点赞图片位置：', p2)
            if (bloo) {
                dzPicChaObj.weizhi = p2;
            }
            sleep(500)
            // 熄灭点赞
            click(p2.x, p2.y)
            sleep(1000)
            return p2;
        } else {
            myLogFunc('点赞图片信息重新尝试失败！')
            return dzPicChaObj.weizhi;
        }
    }
}

/**
 * 上滑视屏，冷却时间一秒
 */
function nextVideo() {
    myLogFunc("上滑")
    // eslint-disable-next-line no-undef
    swipe(device.width * 0.6 + random(-20, 10), device.height * 0.55 + random(-20, 10),
        device.width * 0.62 + random(-20, 10), device.height * 0.35 + random(-20, 10), 1);
    sleep(1000);
    myLogFunc("冷却")
}
/**
 * 下滑视屏，冷却时间一秒
 */
function lastVideo() {
    myLogFunc("下滑")
    // eslint-disable-next-line no-undef
    swipe(device.width * 0.6 + random(-20, 10), device.height * 0.35 + random(-20, 10),
        device.width * 0.62 + random(-20, 10), device.height * 0.55 + random(-20, 10), 1);
    myLogFunc("冷却")
    sleep(1000)
}

// 获取随机数
function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}





